package com.jtech.together.view.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jtech.together.R;
import com.jtech.together.manager.UserManager;
import com.jtech.together.util.ImageUtils;
import com.jtech.together.util.Util;
import com.jtechlib2.adapter.RecyclerAdapter;
import com.jtechlib2.view.RecyclerHolder;

import cn.bmob.newim.bean.BmobIMAudioMessage;
import cn.bmob.newim.bean.BmobIMImageMessage;
import cn.bmob.newim.bean.BmobIMLocationMessage;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMMessageType;
import cn.bmob.newim.bean.BmobIMUserInfo;

/**
 * 聊天消息列表适配器
 * Created by wuxubaiyang on 2017/5/14.
 */

public class ChatMessageAdapter extends RecyclerAdapter<BmobIMMessage> {
    private static final int TYPE_TEXT_LEFT = 0x0001;
    private static final int TYPE_TEXT_RIGHT = 0x0002;
    private static final int TYPE_IMAGE_LEFT = 0x0003;
    private static final int TYPE_IMAGE_RIGHT = 0x0004;
    private static final int TYPE_AUDIO_LEFT = 0x0005;
    private static final int TYPE_AUDIO_RIGHT = 0x0006;
    private static final int TYPE_LOCATION_LEFT = 0x0007;
    private static final int TYPE_LOCATION_RIGHT = 0x0008;
    private static final long MIN_MESSAGE_DATE_SHOW_TIME = 1000 * 60 * 5;

    private ChatMessageListener chatMessageListener;

    public ChatMessageAdapter(Context context) {
        super(context);
    }

    /**
     * 设置聊天消息监听
     *
     * @param chatMessageListener
     */
    public void setChatMessageListener(ChatMessageListener chatMessageListener) {
        this.chatMessageListener = chatMessageListener;
    }

    /**
     * 判断是否为当前用户
     *
     * @param userId
     * @return
     */
    private boolean isMine(String userId) {
        return userId.equals(UserManager.getCurrentUserId());
    }

    @Override
    public int getItemViewType(int position) {
        BmobIMMessage imMessage = getItem(position);
        String type = imMessage.getMsgType();
        int viewType;
        if (type.equals(BmobIMMessageType.IMAGE.getType())) {
            viewType = isMine(imMessage.getFromId()) ?
                    TYPE_IMAGE_RIGHT : TYPE_IMAGE_LEFT;
        } else if (type.equals(BmobIMMessageType.VOICE.getType())) {
            viewType = isMine(imMessage.getFromId()) ?
                    TYPE_AUDIO_RIGHT : TYPE_AUDIO_LEFT;
        } else if (type.equals(BmobIMMessageType.LOCATION.getType())) {
            viewType = isMine(imMessage.getFromId()) ?
                    TYPE_LOCATION_RIGHT : TYPE_LOCATION_LEFT;
        } else {
            viewType = isMine(imMessage.getFromId()) ?
                    TYPE_TEXT_RIGHT : TYPE_TEXT_LEFT;
        }
        return viewType;
    }

    @Override
    protected View createView(LayoutInflater layoutInflater, ViewGroup viewGroup, int viewType) {
        int layoutResource = 0;
        if (viewType == TYPE_TEXT_LEFT) {
            layoutResource = R.layout.view_chat_list_item_text_left;
        } else if (viewType == TYPE_TEXT_RIGHT) {
            layoutResource = R.layout.view_chat_list_item_text_right;
        } else if (viewType == TYPE_IMAGE_LEFT) {
            layoutResource = R.layout.view_chat_list_item_image_left;
        } else if (viewType == TYPE_IMAGE_RIGHT) {
            layoutResource = R.layout.view_chat_list_item_image_right;
        } else if (viewType == TYPE_AUDIO_LEFT) {
            layoutResource = R.layout.view_chat_list_item_audio_left;
        } else if (viewType == TYPE_AUDIO_RIGHT) {
            layoutResource = R.layout.view_chat_list_item_audio_right;
        } else if (viewType == TYPE_LOCATION_LEFT) {
            layoutResource = R.layout.view_chat_list_item_location_left;
        } else if (viewType == TYPE_LOCATION_RIGHT) {
            layoutResource = R.layout.view_chat_list_item_location_right;
        }
        return layoutInflater.inflate(layoutResource, viewGroup, false);
    }

    @Override
    protected void convert(RecyclerHolder holder, BmobIMMessage model, int position) {
        int viewType = getItemViewType(position);
        final BmobIMUserInfo userInfo = model.getBmobIMUserInfo();
        boolean isMine = isMine(model.getFromId());
        //赋值通用参数
        //设置消息时间
        holder.setText(R.id.textview_chat_list_item_date, Util.formatChatMessageDate(model.getCreateTime()));
        //设置是否显示消息时间
        holder.setViewVisible(R.id.textview_chat_list_item_date, position == 0 ||
                (model.getCreateTime() - getItem(position - 1).getCreateTime() > MIN_MESSAGE_DATE_SHOW_TIME));
        //显示用户头像
        ImageUtils.showCircleImage(getContext(), userInfo.getAvatar(), holder.getImageView(R.id.imagebutton_chat_list_item_avatar),
                R.drawable.ic_default_avatar, R.drawable.ic_default_avatar);
        //设置头像点击事件
        holder.setClickListener(R.id.imagebutton_chat_list_item_avatar, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != chatMessageListener) {
                    chatMessageListener.avatarClick(userInfo.getUserId());
                }
            }
        });
        //判断类别,左右作为同一个视图进行赋值
        if (viewType == TYPE_TEXT_LEFT || viewType == TYPE_TEXT_RIGHT) {
            setChatText(holder, model.getContent());
        } else if (viewType == TYPE_IMAGE_LEFT || viewType == TYPE_IMAGE_RIGHT) {
            setChatImage(holder, isMine, BmobIMImageMessage.buildFromDB(isMine, model));
        } else if (viewType == TYPE_AUDIO_LEFT || viewType == TYPE_AUDIO_RIGHT) {
            setChatAudio(holder, isMine, BmobIMAudioMessage.buildFromDB(isMine, model));
        } else if (viewType == TYPE_LOCATION_LEFT || viewType == TYPE_LOCATION_RIGHT) {
            setChatLocation(holder, BmobIMLocationMessage.buildFromDB(model));
        }
    }

    /**
     * 设置文本消息
     *
     * @param holder
     * @param content
     */
    private void setChatText(RecyclerHolder holder, String content) {
        //设置文本消息
        holder.setText(R.id.textview_chat_list_item_text, content);
    }

    /**
     * 设置图片消息
     *
     * @param holder
     * @param imMessage
     */
    private void setChatImage(RecyclerHolder holder, boolean isMine, BmobIMImageMessage imMessage) {
        final String imageUrl = isMine ? imMessage.getLocalPath() : imMessage.getRemoteUrl();
        //显示图片
        ImageUtils.showImage(getContext(), imageUrl,
                holder.getImageView(R.id.imageview_chat_list_item_image));
        //设置卡片点击事件
        holder.setClickListener(R.id.cardview_chat_list_item, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != chatMessageListener) {
                    chatMessageListener.imageClick(imageUrl);
                }
            }
        });
    }

    /**
     * 设置语音消息
     *
     * @param holder
     * @param imMessage
     */
    private void setChatAudio(RecyclerHolder holder, final boolean isMine, final BmobIMAudioMessage imMessage) {
        //设置消息时长
        holder.setText(R.id.textview_chat_list_item_audio,
                Util.formatMediaLength((long) imMessage.getDuration() * 1000));
        //设置消息的点击事件
        holder.setClickListener(R.id.cardview_chat_list_item, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != chatMessageListener) {
                    String[] urls = imMessage.getContent().split("&");
                    chatMessageListener.audioClick(urls[0]);
                }
            }
        });
    }

    /**
     * 设置位置消息
     *
     * @param holder
     * @param imMessage
     */
    private void setChatLocation(RecyclerHolder holder, final BmobIMLocationMessage imMessage) {
        //设置位置描述
        holder.setText(R.id.textview_chat_list_item_location, imMessage.getAddress());
        //设置消息的点击事件
        holder.setClickListener(R.id.cardview_chat_list_item, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != chatMessageListener) {
                    chatMessageListener.locationClick(imMessage.getLatitude(),
                            imMessage.getLongitude(), imMessage.getBmobIMUserInfo().getName(), imMessage.getAddress());
                }
            }
        });
    }

    /**
     * 聊天消息监听
     */
    public interface ChatMessageListener {
        void avatarClick(String targetId);

        void imageClick(String imageUrl);

        void audioClick(String audioUrl);

        void locationClick(double latitude, double longitude, String nickname, String address);
    }
}